#ifndef SP_LOCAL_LOGGER_HANDLER_HPP
#define SP_LOCAL_LOGGER_HANDLER_HPP

#include <condition_variable>
#include <map>
#include <string>
#include <systemd/sd-bus.h>

#include "DbusContext.hpp"

class LocalLoggerHandler : public DbusContext
{
public:
    static constexpr const char* SERVICE_NAME { "com.shz.LocalLoggerHandler" };
    static constexpr const char* SERVICE_PATH { "/com/shz/LocalLoggerHandler" };
    static constexpr const char* SERVICE_INTERFACE { "com.shz.LocalLoggerHandler.Interface" };

    explicit LocalLoggerHandler(
        const std::string& aServiceName, const std::string& aServicePath, const std::string& aServiceInterface);

    ~LocalLoggerHandler() override = default;

    bool prepare() override;

    bool reigsterClient(const std::string& aBusName, pid_t aPid, const std::string& aProcessName);

    bool unregisterClient(const std::string& aBusName);

    int onClientChanged(sd_bus_message *aMessage, void *aUserdata, sd_bus_error *aError);

    bool flushAll();

    bool clearAll();

    int flushAllCallback(sd_bus_message* aMessage, void* aUserdata, sd_bus_error* aError);

    int clearAllCallback(sd_bus_message* aMessage, void* aUserdata, sd_bus_error* aError);

private:
    bool registerInterfaces();

    bool registerDiedWatcher();

    //! clients
    std::map<std::string, std::pair<pid_t, std::string>> mClients;

    std::mutex mClientsMutex;

    std::condition_variable mFlushCondition;

    std::condition_variable mClearCondition;

    uint8_t mClearedCounts { 0 };

    uint8_t mFlushedCounts { 0 };
};

#endif